from fastapi import APIRouter, HTTPException
from app.models.user import User
from app.schemas.user import UserResponse, UserCreate, UserUpdate
from app.utils.pwd_utils import get_password_hash
from tortoise.contrib.pydantic import pydantic_model_creator

router = APIRouter(prefix="/user", tags=["用户管理"])

# 用户 Pydantic 模型，排除密码和删除标志字段
User_Pydantic = pydantic_model_creator(
    User, name="User", exclude=["password", "deleted"]
)


@router.post("/create", response_model=User_Pydantic)
async def create_user(user_data: UserCreate):
    """创建新用户"""
    # 检查用户名是否已存在
    if await User.filter(username=user_data.username).exists():
        raise HTTPException(status_code=400, detail="用户名已存在")

    # 检查邮箱是否已存在
    if await User.filter(email=user_data.email).exists():
        raise HTTPException(status_code=400, detail="邮箱已被注册")
    user_data.password = get_password_hash(user_data.password)
    new_user = await User.create(**user_data.model_dump())
    return await User_Pydantic.from_tortoise_orm(new_user)


@router.get("/list", response_model=list[User_Pydantic])
async def get_users(skip: int = 0, limit: int = 10):
    """获取用户列表"""
    return await User_Pydantic.from_queryset(
        User.filter(deleted=False).offset(skip).limit(limit)
    )


@router.get("/{user_id}", response_model=User_Pydantic)
async def get_user(user_id: int) -> UserResponse:
    """获取指定用户"""
    user = await User.get_or_none(id=user_id, deleted=False)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return await User_Pydantic.from_tortoise_orm(user)


@router.delete("/{user_id}", response_model=dict)
async def delete_user(user_id: int):
    """
    删除用户
    """
    user = await User.get_or_none(id=user_id, deleted=False)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    # 逻辑删除用户
    user.deleted = True
    await user.save()
    return {"detail": "用户已删除"}


@router.put("/update", response_model=User_Pydantic)
async def update_user(user_data: UserUpdate):
    """更新用户信息"""
    user_id = user_data.id
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")

    # 检查用户名是否已存在（排除当前用户）
    if (
        user_data.username
        and await User.filter(username=user_data.username).exclude(id=user_id).exists()
    ):
        raise HTTPException(status_code=400, detail="用户名已存在")

    # 检查邮箱是否已存在（排除当前用户）
    if (
        user_data.email
        and await User.filter(email=user_data.email).exclude(id=user_id).exists()
    ):
        raise HTTPException(status_code=400, detail="邮箱已被注册")

    await User.update(**user.model_dump(exclude_unset=True))
    return await User_Pydantic.from_queryset_single(User.get(id=user_id))
